package com.example.studentgrades.controller;

import com.example.studentgrades.dao.AdminDAO;
import com.example.studentgrades.dao.ScoreDAO;
import com.example.studentgrades.dao.StudentDAO;
import com.example.studentgrades.model.Admin;

import com.example.studentgrades.model.Score;
import com.example.studentgrades.model.Student;
import com.example.studentgrades.util.ConnectionManager;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/admin/*")
public class AdminServlet extends BaseServlet {

    private StudentDAO studentDAO;
    private ScoreDAO scoreDAO;

    public void init() {
        Connection connection = null;
        try {
            connection = ConnectionManager.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        studentDAO = new StudentDAO(connection);
        scoreDAO = new ScoreDAO(connection);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo.equals("/login")) {
            login(request, response);
        }
        try{
            if (pathInfo.equals("/update_student")) {
                updateStudent(request,response);
            }
            if (pathInfo.equals("/update_score")) {
                updateScore(request,response);
            }
            if (pathInfo.equals("/add_student")) {
                addStudent(request,response);
            }
            if (pathInfo.equals("/add_score")) {
                addScore(request,response);
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
            redirectToPage(response, "admin_home.jsp"); // 登录成功后跳转到管理员首页
        }

    }

    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Student student = new Student();
        student.setUsername(username);
        student.setPassword(password);
        try (Connection connection = getConnection()) {
            StudentDAO studentDAO = new StudentDAO(connection);
            studentDAO.addStudent(student);
            redirectToPage(response, "manage_students.jsp");
        } catch (Exception e) {
            redirectToPage(response, "manage_students.jsp");
        }
    }

    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        int studentId = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Student student = new Student();
        student.setStudentId(studentId);
        student.setUsername(username);
        student.setPassword(password);
        try (Connection connection = getConnection()) {
            StudentDAO studentDAO = new StudentDAO(connection);
            studentDAO.updateStudent(student);
            redirectToPage(response, "manage_students.jsp");
        } catch (Exception e) {
            redirectToPage(response, "manage_students.jsp");
        }
    }

    private void addScore(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        String subject = request.getParameter("subject");
        int scoreValue = Integer.parseInt(request.getParameter("score"));
        Score score = new Score();
        score.setStudentId(studentId);
        score.setSubject(subject);
        score.setScore(scoreValue);
        try (Connection connection = getConnection()) {
            ScoreDAO scoreDAO = new ScoreDAO(connection);
            scoreDAO.addScore(score);
            redirectToPage(response, "manage_scores.jsp");
        } catch (Exception e) {
            redirectToPage(response, "manage_scores.jsp");
        }
    }

    private void updateScore(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        int scoreId = Integer.parseInt(request.getParameter("id"));
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        String subject = request.getParameter("subject");
        int scoreValue = Integer.parseInt(request.getParameter("score"));
        Score score = new Score();
        score.setScoreId(scoreId);
        score.setStudentId(studentId);
        score.setSubject(subject);
        score.setScore(scoreValue);
        try (Connection connection = getConnection()) {
            ScoreDAO scoreDAO = new ScoreDAO(connection);
            scoreDAO.updateScore(score);
            redirectToPage(response, "manage_scores.jsp");
        } catch (Exception e) {
            redirectToPage(response, "manage_scores.jsp");
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        if (pathInfo.equals("/login")) {
            login(request, response);
        }
        if (pathInfo.equals("/delete_student")) {
            deleteStudent(request,response);
        }

        if (pathInfo.equals("/delete_score")) {
            deleteScores(request,response);
        }
        // 可以添加更多操作的处理，比如学生信息管理、成绩管理等
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try (Connection connection = getConnection()) {
            AdminDAO adminDAO = new AdminDAO(connection);
            Admin admin = adminDAO.findAdminByUsernameAndPassword(username, password);
            if (admin != null) {
                HttpSession session = request.getSession();
                session.setAttribute("admin", admin);
                redirectToPage(response, "admin_home.jsp"); // 登录成功后跳转到管理员首页
            } else {
                redirectToPage(response, "admin_login.jsp"); // 登录失败返回登录页面
            }
        } catch (SQLException e) {
            handleSQLException(response, e, "admin_login.jsp"); // 登录失败返回登录页面
        }
    }

    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try (Connection connection = getConnection()) {
            StudentDAO studentDAO = new StudentDAO(connection);
            String id = request.getParameter("id");
            studentDAO.deleteStudent(Integer.parseInt(id));
            redirectToPage(response, "manage_students.jsp"); // 登录成功后跳转到管理员首页
        } catch (SQLException e) {
            handleSQLException(response, e, "manage_students.jsp"); // 登录失败返回登录页面
        }
    }

    private void deleteScores(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try (Connection connection = getConnection()) {
            ScoreDAO scoreDAO = new ScoreDAO(connection);
            String id = request.getParameter("id");
            scoreDAO.deleteScore(Integer.parseInt(id));
            redirectToPage(response, "manage_scores.jsp"); // 登录成功后跳转到管理员首页
        } catch (SQLException e) {
            handleSQLException(response, e, "manage_scores.jsp"); // 登录失败返回登录页面
        }
    }
}
